import { useState, useEffect, useCallback } from 'react';
import { Empty, InfiniteScroll, List } from 'antd-mobile';
import { InbizIcon, useEvents } from '@inbiz/utils';
import TitleLogo from '../../web/view/TitleLogo';
import { getNewsList as getNewsListData } from '../../../service';
import { getMessage } from '@inbiz/react';

const stream = (props: any) => {
  // 列表数据
  const [listData, $listData] = useState<any[]>([]);

  // 是否还有数据
  const [hasMore, $hasMore] = useState(true);

  // 加载页数
  const [pageIndex, $pageIndex] = useState<number>(0);
  const [configEvents] = useEvents(props.callBackEvents, props.emit)

  const getNewsList = useCallback(async (params: object) => {
      const newParams = (await configEvents.current?.onParams?.(params)) || params;
      const data = await (configEvents.current?.onRequest || getNewsListData)(newParams as any)
      return await configEvents.current?.onData?.(data) || data
    }, []);

  // 初始化
  useEffect(() => {
    getList(1);
  }, [props?.fixNewKey?.length, props.everytimeLoad?.threshold]);

  const getList = async (page: number) => {
    const res: News.NewsList = await getNewsList({
      categoryId: props?.fixNewKey?.map((item:any)=>{return item.id}).toString(),
      pageIndex: page,
      pageSize: props.everytimeLoad?.threshold,
      showNew: props.standOut?.isStandout,
      numNew: props.standOut?.threshold || undefined,
    });
    if (!res?.PageIndex) {
      $listData([]);
    } else if (res?.PageIndex == 1) {
      $listData([...res?.ContentList]);
    } else {
      $listData((listData) => [...listData, ...res?.ContentList]);
    }
    $pageIndex(res?.PageIndex);
    $hasMore(res?.ContentList?.length > 0);
  };

  const loadMore = async () => {
    await getList(pageIndex + 1);
  };

  return (
    <>{listData?.length>0?  <>
      <List className="list-content">
        {listData?.map((item) => {
          return (
            <List.Item onClick={() => props.goToDetail(item)} clickable={false} key={item.ID}>
              <span className="list-item">
                {props.listLogo && <TitleLogo listLogo={props.listLogo} />}
                {props.showCate && <span>【{item.ContentCategoryName}】</span>}
                <div className="title-text">{item.Title}</div>
                <div className="title-tag">{item.IsNew && <span>NEW</span>}</div>
              </span>
              <span className="content-time">{item.CreateTime}</span>
            </List.Item>
          );
        })}
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10} />
    </>:<Empty
      image={<InbizIcon type="icon-ic-zanwushuju" style={{ fontSize: '50px' }} />}
      description={getMessage('News.noData')}
  />}</>
  
  );
};
export default stream;
